<?php

/**
 * 登录
 */
namespace app\ph\controller;

use app\common\model\Record;
use think\App;
use think\Controller;
use think\facade\Request;

class Login extends Controller
{
    protected $admin_model;
    protected $record_model;

    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->admin_model  = new \app\common\model\Admin();
        $this->record_model = new Record();
    }

    /**
     * 创建初始账号
     * @return \think\response\Json
     */
    public function initial()
    {
        $res = $this->admin_model->save(
            [
                'create_time' => time(),
                'update_time' => time(),
                'name'        => 'shenlin',
                'pass'        => getPassRule('shenlin'),
                'status'      => 1,
                'type'        => 1
            ]
        );
        return operationResult($res);
    }

    /**
     * 登录
     * @return \think\response\View
     */
    public function index()
    {
        // 临时关闭模板布局
        $this->view->engine->layout(false);
        return view("login/index");
    }

    /**
     * 登录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $userName = input('post.name');
        $userPass = input('post.pass');
        $code     = input('post.code');
        if (!captcha_check($code)) {
            return json(['code' => 100, 'message' => '验证码错误']);
        }
        if (!$userName || !$userPass) {
            return json(['code' => 101, 'message' => '请填写账号或密码']);
        }
        $res = $this->admin_model->getOne(['name' => $userName], 'id,pass,status,type', 'id desc');
        if (!$res) {
            return json(['code' => 102, 'message' => '账号或密码错误']);
        }
        if ($res['status'] == 0) {
            return json(['code' => 103, 'message' => '您的账户已冻结']);
        }
        if (getPassRule($userPass) !== $res['pass']) {
            return json(['code' => 104, 'message' => '账号或密码错误']);
        }
        session('userName', $userName, 'phCms');
        session('userId', $res['id'], 'phCms');
        session('userType', $res['type'], 'phCms');
        // 写 登录记录
        $this->record_model->addData(['ip' => Request::ip()]);
        return json(['code' => 200, 'message' => '登录成功', 'jumpAddress' => url('Index/index')]);
    }

    /**
     * 退出登录
     */
    public function out()
    {
        session(null, 'phCms');
        return json(['code' => 200, 'message' => '成功退出']);
    }
}
